package com.primb.bench.project.home.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.primb.baselibs.view.AutoToolbar;
import com.primb.bench.R;
import com.primb.bench.base.SwipeBaseActivity;
import com.primb.bench.common.constant.AppConstant;
import com.primb.bench.common.module.repository.LoanEnsureRepository;
import com.primb.bench.common.override.HttpSubscriber;
import com.primb.bench.project.home.adapter.LoanEnsureMenuAdapter;
import com.primb.bench.project.home.entity.EnsureInfoEntity;
import com.primb.bench.project.home.entity.EnsureObjectEntity;
import com.primb.bench.project.home.entity.HttpEnsureMoneyEntity;
import com.primb.bench.project.home.entity.HttpStrEntity;
import com.primb.bench.project.home.entity.RequestObjectEntity;
import com.primb.netlibs.exception.ApiException;
import com.yanzhenjie.recyclerview.swipe.Closeable;
import com.yanzhenjie.recyclerview.swipe.OnSwipeMenuItemClickListener;
import com.yanzhenjie.recyclerview.swipe.SwipeMenu;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuCreator;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuItem;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuRecyclerView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import rx.Subscription;
import rx.subscriptions.CompositeSubscription;

import static com.primb.bench.common.constant.AppConstant.ADD_ENSURE_OBJECT_RESULT;
import static com.primb.bench.common.constant.AppConstant.ADD_ENSURE_OBJECT_TYPE;
import static com.primb.bench.common.constant.AppConstant.EDIT_ENSURE_OBJECT_RESULT;
import static com.primb.bench.common.constant.AppConstant.EDIT_ENSURE_OBJECT_TYPE;

/**
 * Created by Chen on 2017/5/4.
 * 功能描述：
 */

public class LoanEnsureActivity extends SwipeBaseActivity {

    @BindView(R.id.title_bar)
    TextView titleBar;
    @BindView(R.id.tool_bar)
    AutoToolbar toolBar;
    @BindView(R.id.recycler_add_info)
    SwipeMenuRecyclerView recyclerAddInfo;
    @BindView(R.id.iv_top)
    ImageView ivTop;
    @BindView(R.id.swipe_content)
    SwipeRefreshLayout swipeContent;
    @BindView(R.id.btn_ensure_object_save)
    Button btnEnsureObjectSave;
    private ArrayList<EnsureObjectEntity> dataList;
    private LoanEnsureMenuAdapter mMenuAdapter;
    /**
     * 菜单创建器。在Item要创建菜单的时候调用。
     */
    private SwipeMenuCreator swipeMenuCreator = new SwipeMenuCreator() {
        @Override
        public void onCreateMenu(SwipeMenu swipeLeftMenu, SwipeMenu swipeRightMenu, int viewType) {
            int width = getResources().getDimensionPixelSize(R.dimen.item_width);

            // MATCH_PARENT 自适应高度，保持和内容一样高；也可以指定菜单具体高度，也可以用WRAP_CONTENT。
            int height = ViewGroup.LayoutParams.MATCH_PARENT;

            // 添加右侧的，如果不添加，则右侧不会出现菜单。
            {
                SwipeMenuItem deleteItem = new SwipeMenuItem(LoanEnsureActivity.this)
                        .setBackgroundDrawable(R.drawable.selector_red)
                        .setImage(R.mipmap.ic_action_delete)
                        .setText("删除") // 文字，还可以设置文字颜色，大小等。。
                        .setTextColor(Color.WHITE)
                        .setWidth(width)
                        .setHeight(height);
                swipeRightMenu.addMenuItem(deleteItem);// 添加一个按钮到右侧侧菜单。
            }
        }
    };

    /**
     * 菜单点击监听。
     */
    private OnSwipeMenuItemClickListener menuItemClickListener = new OnSwipeMenuItemClickListener() {
        /**
         * Item的菜单被点击的时候调用。
         * @param closeable       closeable. 用来关闭菜单。
         * @param adapterPosition adapterPosition. 这个菜单所在的item在Adapter中position。
         * @param menuPosition    menuPosition. 这个菜单的position。比如你为某个Item创建了2个MenuItem，那么这个position可能是是 0、1，
         * @param direction       如果是左侧菜单，值是：SwipeMenuRecyclerView#LEFT_DIRECTION，如果是右侧菜单，值是：SwipeMenuRecyclerView#RIGHT_DIRECTION.
         */
        @Override
        public void onItemClick(Closeable closeable, int adapterPosition, int menuPosition, int direction) {
            closeable.smoothCloseMenu();// 关闭被点击的菜单。
            if (menuPosition == 0) {// 删除按钮被点击。
                deleteEnsureObject(dataList.get(adapterPosition).getGuatantId(), adapterPosition);
            }
        }
    };
    private EnsureInfoEntity info;
    private String priceId;
    private CompositeSubscription subscription;
    private boolean isEdit;
    private boolean isView;

    @Override
    protected void onBaseIntent() {
        super.onBaseIntent();
        Intent intent = getIntent();
        isEdit = intent.getBooleanExtra("isEdit", true);
        info = intent.getParcelableExtra("info");
        priceId = intent.getStringExtra("priceId");

        isView = intent.getBooleanExtra("isView", false);
    }

    @Override
    protected int onBaseLayoutId(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_ensure_object;
    }

    @Override
    protected void onBaseBindView() {
        titleBar.setText("担保质押物");
        ivTop.setVisibility(View.VISIBLE);
        ivTop.setImageResource(R.mipmap.add_top_icon);
        toolBar.setNavigationOnClickListener(v -> {
            if (!isView)
                saveObjectList();
            else
                LoanEnsureActivity.this.finish();
        });

        swipeContent.setColorSchemeColors(ContextCompat.getColor(this, android.R.color.holo_blue_bright), ContextCompat.getColor(this, android.R.color.holo_green_light),
                ContextCompat.getColor(this, android.R.color.holo_orange_light), ContextCompat.getColor(this, android.R.color.holo_red_light));
        swipeContent.setRefreshing(false);
        swipeContent.setOnRefreshListener(() -> {
            onLoadData();
        });

        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerAddInfo.setLayoutManager(layoutManager);
        recyclerAddInfo.setHasFixedSize(true);
        recyclerAddInfo.setItemAnimator(new DefaultItemAnimator());
        dataList = new ArrayList<>();
        // 为SwipeRecyclerView的Item创建菜单
        // 设置菜单创建器。
        if (isEdit) {
            recyclerAddInfo.setSwipeMenuCreator(swipeMenuCreator);

            // 设置菜单Item点击监听。
            recyclerAddInfo.setSwipeMenuItemClickListener(menuItemClickListener);
        }
        mMenuAdapter = new LoanEnsureMenuAdapter(dataList, isEdit);
//        mMenuAdapter.setOnItemClickListener((adapter, view, position) -> {
//            Intent intent = new Intent();
//            intent.putExtra("info", dataList.get(position));
//                LoanEnsureActivity.this.setResult(AppConstant.ADD_ENSURE_OBJECT_INFO, intent);
//            LoanEnsureActivity.this.finish();
//        });
        if (isEdit) {
            mMenuAdapter.setOnItemChildClickListener((adapter, view, position) -> {
                switch (view.getId()) {
                    case R.id.iv_ensure_edit:
                        Intent intent = new Intent(LoanEnsureActivity.this, AddEnsureInfoActivity.class);
                        intent.putExtra("type", info.getEnsureMainType());
                        intent.putExtra("info", dataList.get(position));
                        intent.putExtra("priceId", priceId);
                        startActivityForResult(intent, EDIT_ENSURE_OBJECT_TYPE);
                        break;
                }
            });
        }
        recyclerAddInfo.setAdapter(mMenuAdapter);

        subscription = new CompositeSubscription();

        if (!isEdit) {
            btnEnsureObjectSave.setVisibility(View.GONE);
            ivTop.setVisibility(View.GONE);
        }
    }

    @Override
    protected void onLoadData() {
        RequestObjectEntity entity = new RequestObjectEntity();
        entity.setPriceId(priceId);
        showLoadingDialog("加载中");
        Subscription subscribe = LoanEnsureRepository.getEnsureObjectListEntity(entity).subscribe(new HttpSubscriber<List<EnsureObjectEntity>>(this) {
            @Override
            public void onCompleted() {
                hideLoadingDialog();
                swipeContent.setRefreshing(false);
            }

            @Override
            public void onNext(List<EnsureObjectEntity> list) {
                dataList.clear();
                dataList.addAll(list);
                if (dataList.size() > 0 && isEdit) {
                    btnEnsureObjectSave.setVisibility(View.VISIBLE);
                }
                mMenuAdapter.notifyDataSetChanged();
            }

            @Override
            public void onError(ApiException e) {
                dataList.clear();
                btnEnsureObjectSave.setVisibility(View.GONE);
                mMenuAdapter.notifyDataSetChanged();
                hideLoadingDialog();
                showToast(e.getMessage());
                swipeContent.setRefreshing(false);
            }
        });
        subscription.add(subscribe);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == ADD_ENSURE_OBJECT_TYPE && resultCode == ADD_ENSURE_OBJECT_RESULT) {
            onLoadData();
        } else if (requestCode == EDIT_ENSURE_OBJECT_TYPE && resultCode == EDIT_ENSURE_OBJECT_RESULT) {
            onLoadData();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        subscription.clear();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && !isView) {
            saveObjectList();
            return false;
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }

    @OnClick({R.id.iv_top, R.id.btn_ensure_object_save})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_top:
                Intent intent = new Intent(LoanEnsureActivity.this, AddEnsureInfoActivity.class);
                intent.putExtra("type", info.getEnsureMainType());
                intent.putExtra("priceId", priceId);
                startActivityForResult(intent, ADD_ENSURE_OBJECT_TYPE);
                break;
            case R.id.btn_ensure_object_save:
                saveObjectList();
                break;
        }
    }

    private void saveObjectList() {
        showLoadingDialog("加载中");
        Subscription subscribe = LoanEnsureRepository.saveObjectList(priceId).subscribe(new HttpSubscriber<HttpEnsureMoneyEntity.DataBean>(this) {
            @Override
            public void onCompleted() {
                hideLoadingDialog();
            }

            @Override
            public void onNext(HttpEnsureMoneyEntity.DataBean o) {
                info = getIntent().getParcelableExtra("info");
                info.setLnFinImpawnAmt(o.getLnFinImpawnAmt());
                info.setLnPropertyAmt(o.getLnPropertyAmt());
                info.setLnAcctRecvAmt(o.getLnAcctRecvAmt());
                info.setLnOthMortAmt(o.getLnOthMortAmt());
                info.setHighGuarantee(o.getHighGuaranteeAmt());
                info.setCommonGuarantee(o.getCommonGuaranteeAmt());
                Intent intent = new Intent();
                intent.putExtra("info", info);
                setResult(AppConstant.ENSURE_OBJECT_RESULT, intent);
                LoanEnsureActivity.this.finish();
            }

            @Override
            public void onError(ApiException e) {
                hideLoadingDialog();
                showToast(e.getMessage());
            }
        });
        subscription.add(subscribe);
    }

    private void deleteEnsureObject(String guatantId, int adapterPosition) {
        showLoadingDialog("加载中");
        Subscription subscribe = LoanEnsureRepository.deleteEnsureObject(guatantId).subscribe(new HttpSubscriber<HttpStrEntity>(this) {
            @Override
            public void onCompleted() {
                hideLoadingDialog();
            }

            @Override
            public void onNext(HttpStrEntity o) {
                showToast(o.getData());
                dataList.remove(adapterPosition);
                mMenuAdapter.notifyItemRemoved(adapterPosition);
            }

            @Override
            public void onError(ApiException e) {
                hideLoadingDialog();
                showToast(e.getMessage());
            }
        });
        subscription.add(subscribe);
    }
}
